package site.isscloud.common.core.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import site.isscloud.common.core.domain.AjaxResult;
import site.isscloud.common.core.service.IExcelImportService;
import site.isscloud.common.utils.poi.ExcelUtil;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通用导入控制器基类
 */
public abstract class BaseImportController<T> extends BaseController {

    /**
     * 导入数据
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file,
                                 @RequestParam(defaultValue = "false") boolean updateSupport,
                                 @RequestParam Map<String, Object> params) throws Exception {
        ExcelUtil<T> util = new ExcelUtil<T>(getEntityClass());
        List<T> dataList = util.importExcel(file.getInputStream());
        String message = getImportService().importData(dataList, updateSupport, params);
        return success(message);
    }

    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<T> util = new ExcelUtil<T>(getEntityClass());
        util.importTemplateExcel(response, getTemplateName());
    }

    // 抽象方法，由子类实现
    protected abstract Class<T> getEntityClass();
    protected abstract IExcelImportService<T> getImportService();
    protected abstract String getTemplateName();
}